//
//  WaterfallGrid.swift
//  shop
//
//  Created by chen on 2025/5/13.
//

import SwiftUI

struct WaterfallGrid<Content: View>: View {
    let items: [GoodsItem]
    let columns: Int
    let content: (GoodsItem) -> Content
    
    init(items: [GoodsItem],
         columns: Int = 2,
         @ViewBuilder content: @escaping (GoodsItem) -> Content) {
        self.items = items
        self.columns = columns
        self.content = content
    }
    
    private var rows: [[GoodsItem]] {
        var result: [[GoodsItem]] = Array(repeating: [], count: columns)
        items.enumerated().forEach { index, item in
            result[index % columns].append(item)
        }
        return result
    }
    
    var body: some View {
        HStack(alignment: .top, spacing: 8) {
            ForEach(0..<columns, id: \.self) { columnIndex in
                LazyVStack(spacing: 8) {
                    ForEach(rows[columnIndex], id: \.id) { item in
                        content(item)
                    }
                }
            }
        }
        .padding(.horizontal, 10)
    }
}
